package com.cq.config;

import com.cq.pojo.Admin;
import com.cq.pojo.Permission;
import com.cq.pojo.Role;
import com.cq.pojo.User;
import com.cq.service.AdminService;
import com.cq.service.PermissionService;
import com.cq.service.RoleService;
import com.cq.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


/**
 * @Author: 悠久的苍穹
 * @Date: 2020/7/6 14:27
 * @Description: ${description}
 * @Version: 1.0
 */
public class UserRealm extends AuthorizingRealm {


    @Autowired
    AdminService adminService;
    @Autowired
    RoleService roleService;
    @Autowired
    PermissionService permissionService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        Admin admin = (Admin) subject.getPrincipal();
        Role role = roleService.findRoleByAdminId(admin.getId());
        List<Permission> list = permissionService.findPermissionByRole(role);
        for (Permission permission:list){
            simpleAuthorizationInfo.addStringPermission(permission.getUrl());
        }
        return simpleAuthorizationInfo;
    }


    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        //连接真实数据库
        Admin admin = adminService.findAdminByName(userToken.getUsername());
        if(!userToken.getUsername().equals(admin.getName())){
            //抛出异常UnknownAccountException
            return null;
        }
        return new SimpleAuthenticationInfo(admin,admin.getPassword(),"");
    }
}
